<template>
  <div class="work-log-detail-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <el-button 
        @click="goBack" 
        :icon="ArrowLeft" 
        circle 
        size="small"
        class="back-btn"
      />
      <h2 class="page-title">{{ dateText }} 工作记录</h2>
      <div class="header-actions">
        <el-button 
          type="primary" 
          size="small" 
          @click="showAddLogDialog = true"
          :icon="Plus"
        >
          添加
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-card">
      <div class="stat-item">
        <div class="stat-number">{{ workLogs.length }}</div>
        <div class="stat-label">总记录数</div>
      </div>
      <div class="stat-item">
        <div class="stat-number">{{ uniqueClientsCount }}</div>
        <div class="stat-label">拜访客户</div>
      </div>
      <div class="stat-item">
        <div class="stat-number">{{ uniqueServicesCount }}</div>
        <div class="stat-label">服务项目</div>
      </div>
    </div>

    <!-- 工作记录列表 -->
    <div class="logs-container">
      <div class="logs-header">
        <h3>详细记录</h3>
        <el-select 
          v-model="filterServiceId" 
          placeholder="筛选服务项目" 
          clearable
          size="small"
          style="width: 140px"
        >
          <el-option
            v-for="service in availableServices"
            :key="service.id"
            :label="service.serviceName"
            :value="service.id"
          />
        </el-select>
      </div>

      <div class="logs-list" v-if="filteredLogs.length > 0">
        <div 
          v-for="log in filteredLogs" 
          :key="log.id"
          class="log-card"
        >
          <div class="log-header">
            <div class="client-info">
              <h4 class="client-name">{{ log.client.clientName }}</h4>
              <span class="client-code">{{ log.client.clientCode }}</span>
            </div>
            <el-dropdown @command="handleLogAction">
              <el-button :icon="MoreFilled" circle size="small" text />
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :command="{ action: 'edit', log }">
                    <el-icon><Edit /></el-icon>
                    编辑
                  </el-dropdown-item>
                  <el-dropdown-item :command="{ action: 'delete', log }" divided>
                    <el-icon><Delete /></el-icon>
                    删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>

          <div class="log-content">
            <div class="client-details">
              <el-tag size="small">{{ log.client.marketType }}</el-tag>
              <el-tag size="small" type="info">{{ log.client.terminalType }}</el-tag>
            </div>

            <div class="service-info">
              <el-tag type="success" size="small">{{ log.service.serviceName }}</el-tag>
            </div>

            <div class="log-notes" v-if="log.notes">
              <div class="notes-label">备注：</div>
              <div class="notes-content">{{ log.notes }}</div>
            </div>

            <div class="log-time">
              记录时间：{{ formatDateTime(log.createdAt) }}
            </div>
          </div>
        </div>
      </div>

      <div class="empty-logs" v-else>
        <el-empty description="暂无工作记录" :image-size="100">
          <el-button type="primary" @click="showAddLogDialog = true">
            添加第一条记录
          </el-button>
        </el-empty>
      </div>
    </div>

    <!-- 添加工作日志对话框 -->
    <el-dialog
      v-model="showAddLogDialog"
      title="添加工作记录"
      width="90%"
      :before-close="handleCloseAddDialog"
    >
      <el-form :model="addLogForm" label-position="top">
        <el-form-item label="选择客户">
          <el-input
            v-model="clientSearchKeyword"
            placeholder="输入客户代码或店名搜索"
            @input="searchClients"
            clearable
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          
          <div class="client-search-results" v-if="searchResults.length > 0">
            <div 
              v-for="client in searchResults" 
              :key="client.id"
              class="client-option"
              :class="{ selected: addLogForm.clientId === client.id }"
              @click="selectClient(client)"
            >
              <div class="client-info">
                <span class="client-name">{{ client.clientName }}</span>
                <span class="client-code">{{ client.clientCode }}</span>
              </div>
              <div class="client-details">
                <el-tag size="small">{{ client.marketType }}</el-tag>
                <el-tag size="small" type="info">{{ client.terminalType }}</el-tag>
              </div>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="选择服务项目" v-if="addLogForm.clientId">
          <div class="service-options">
            <el-checkbox-group v-model="addLogForm.serviceIds">
              <el-checkbox 
                v-for="service in availableServices" 
                :key="service.id"
                :label="service.id"
                class="service-checkbox"
              >
                {{ service.serviceName }}
              </el-checkbox>
            </el-checkbox-group>
          </div>
        </el-form-item>

        <el-form-item label="备注">
          <el-input
            v-model="addLogForm.notes"
            type="textarea"
            :rows="3"
            placeholder="请输入工作备注（可选）"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showAddLogDialog = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="submitAddLog"
          :loading="submitting"
          :disabled="!canSubmit"
        >
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 编辑工作日志对话框 -->
    <el-dialog
      v-model="showEditLogDialog"
      title="编辑工作记录"
      width="90%"
    >
      <el-form :model="editLogForm" label-position="top">
        <el-form-item label="客户信息">
          <div class="selected-client-info">
            <span class="client-name">{{ editLogForm.clientName }}</span>
            <span class="client-code">{{ editLogForm.clientCode }}</span>
          </div>
        </el-form-item>

        <el-form-item label="服务项目">
          <div class="selected-service-info">
            <el-tag type="success">{{ editLogForm.serviceName }}</el-tag>
          </div>
        </el-form-item>

        <el-form-item label="备注">
          <el-input
            v-model="editLogForm.notes"
            type="textarea"
            :rows="3"
            placeholder="请输入工作备注（可选）"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showEditLogDialog = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="submitEditLog"
          :loading="submitting"
        >
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  ArrowLeft, 
  Plus, 
  MoreFilled, 
  Edit, 
  Delete, 
  Search 
} from '@element-plus/icons-vue'
import { trpc } from '@/utils/trpc'
import { AuthUtils } from '@/utils/auth'

const route = useRoute()
const router = useRouter()

// 响应式数据
const workLogs = ref([])
const availableServices = ref([])
const filterServiceId = ref(null)
const showAddLogDialog = ref(false)
const showEditLogDialog = ref(false)
const submitting = ref(false)
const clientSearchKeyword = ref('')
const searchResults = ref([])

// 表单数据
const addLogForm = ref({
  clientId: null,
  serviceIds: [],
  notes: ''
})

const editLogForm = ref({
  id: null,
  clientName: '',
  clientCode: '',
  serviceName: '',
  notes: ''
})

// 计算属性
const dateText = computed(() => {
  const dateStr = route.params.date as string
  // 解析日期字符串，避免时区问题
  const [year, month, day] = dateStr.split('-').map(Number)
  return `${month}月${day}日`
})

const filteredLogs = computed(() => {
  if (!filterServiceId.value) return workLogs.value
  return workLogs.value.filter(log => log.serviceId === filterServiceId.value)
})

const uniqueClientsCount = computed(() => {
  const clientIds = new Set(workLogs.value.map(log => log.clientId))
  return clientIds.size
})

const uniqueServicesCount = computed(() => {
  const serviceIds = new Set(workLogs.value.map(log => log.serviceId))
  return serviceIds.size
})

const canSubmit = computed(() => {
  return addLogForm.value.clientId && addLogForm.value.serviceIds.length > 0
})

// 方法
const goBack = () => {
  router.back()
}

const loadWorkLogs = async () => {
  try {
    const managerId = getCurrentManagerId()
    if (!managerId) return
    
    const result = await trpc.workLog.byDate.query({
      managerId,
      date: `${route.params.date}T00:00:00.000Z`
    })
    
    if (result.success) {
      workLogs.value = result.data
    }
  } catch (error) {
    console.error('加载工作日志失败:', error)
    ElMessage.error('加载工作日志失败')
  }
}

const loadAvailableServices = async () => {
  try {
    const result = await trpc.service.list.query({ pageSize: 100 })
    if (result.success) {
      availableServices.value = result.data.data
    }
  } catch (error) {
    console.error('加载服务项目失败:', error)
  }
}

const searchClients = async () => {
  if (!clientSearchKeyword.value.trim()) {
    searchResults.value = []
    return
  }
  
  try {
    const managerId = getCurrentManagerId()
    if (!managerId) return
    
    const result = await trpc.workLog.searchClients.query({
      managerId,
      keyword: clientSearchKeyword.value.trim()
    })
    
    if (result.success) {
      searchResults.value = result.data
    }
  } catch (error) {
    console.error('搜索客户失败:', error)
  }
}

const selectClient = (client: any) => {
  addLogForm.value.clientId = client.id
  searchResults.value = []
  clientSearchKeyword.value = `${client.clientName} (${client.clientCode})`
}

const submitAddLog = async () => {
  if (!canSubmit.value) return
  
  submitting.value = true
  try {
    const managerId = getCurrentManagerId()
    if (!managerId) return
    
    // 为每个选中的服务创建工作日志
    for (const serviceId of addLogForm.value.serviceIds) {
      await trpc.workLog.create.mutate({
        managerId,
        clientId: addLogForm.value.clientId,
        serviceId,
        // 统一策略：completionDate 固定为当天 00:00:00.000Z
        completionDate: `${route.params.date}T00:00:00.000Z`,
        notes: addLogForm.value.notes || undefined
      })
    }
    
    ElMessage.success('工作记录添加成功')
    showAddLogDialog.value = false
    await loadWorkLogs()
  } catch (error) {
    console.error('添加工作记录失败:', error)
    ElMessage.error('添加工作记录失败')
  } finally {
    submitting.value = false
  }
}

const handleLogAction = async (command: any) => {
  const { action, log } = command
  
  if (action === 'edit') {
    editLogForm.value = {
      id: log.id,
      clientName: log.client.clientName,
      clientCode: log.client.clientCode,
      serviceName: log.service.serviceName,
      notes: log.notes || ''
    }
    showEditLogDialog.value = true
  } else if (action === 'delete') {
    try {
      await ElMessageBox.confirm('确定要删除这条工作记录吗？', '确认删除', {
        type: 'warning'
      })
      
      await trpc.workLog.delete.mutate({
        id: log.id.toString(),
        managerId: getCurrentManagerId()
      })
      
      ElMessage.success('删除成功')
      await loadWorkLogs()
    } catch (error) {
      if (error !== 'cancel') {
        console.error('删除工作记录失败:', error)
        ElMessage.error('删除失败')
      }
    }
  }
}

const submitEditLog = async () => {
  // 这里应该调用更新API，但目前API中没有更新方法
  // 暂时只更新备注，实际项目中需要添加更新API
  ElMessage.info('编辑功能待完善')
  showEditLogDialog.value = false
}

const handleCloseAddDialog = () => {
  addLogForm.value = {
    clientId: null,
    serviceIds: [],
    notes: ''
  }
  clientSearchKeyword.value = ''
  searchResults.value = []
  showAddLogDialog.value = false
}

const formatDateTime = (dateTime: string) => {
  const date = new Date(dateTime)
  return `${date.getMonth() + 1}月${date.getDate()}日 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
}

const getCurrentManagerId = () => {
  const user = AuthUtils.getUser<any>()
  return user?.id || null
}

// 生命周期
onMounted(() => {
  loadWorkLogs()
  loadAvailableServices()
})
</script>

<style scoped>
.work-log-detail-page {
  background: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  background: white;
  border-bottom: 1px solid #ebeef5;
}

.page-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  flex: 1;
  text-align: center;
}

.back-btn {
  width: 32px;
  height: 32px;
}

.stats-card {
  display: flex;
  background: white;
  margin: 12px;
  border-radius: 8px;
  padding: 20px;
  gap: 20px;
}

.stat-item {
  flex: 1;
  text-align: center;
}

.stat-number {
  font-size: 24px;
  font-weight: 600;
  color: #409eff;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  color: #909399;
}

.logs-container {
  background: white;
  margin: 12px;
  border-radius: 8px;
  overflow: hidden;
}

.logs-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
}

.logs-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.logs-list {
  padding: 0;
}

.log-card {
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
}

.log-card:last-child {
  border-bottom: none;
}

.log-header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  margin-bottom: 12px;
}

.client-info h4 {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 500;
}

.client-code {
  font-size: 12px;
  color: #909399;
}

.log-content {
  space-y: 8px;
}

.client-details {
  display: flex;
  gap: 8px;
  margin-bottom: 8px;
}

.service-info {
  margin-bottom: 8px;
}

.log-notes {
  background: #f5f7fa;
  padding: 8px 12px;
  border-radius: 4px;
  margin-bottom: 8px;
}

.notes-label {
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
}

.notes-content {
  font-size: 14px;
  color: #606266;
  line-height: 1.4;
}

.log-time {
  font-size: 12px;
  color: #c0c4cc;
}

.empty-logs {
  padding: 60px 20px;
}

.client-search-results {
  max-height: 200px;
  overflow-y: auto;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  margin-top: 8px;
}

.client-option {
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.2s;
}

.client-option:hover {
  background: #f5f7fa;
}

.client-option.selected {
  background: #e6f7ff;
}

.client-option:last-child {
  border-bottom: none;
}

.service-options {
  max-height: 200px;
  overflow-y: auto;
}

.service-checkbox {
  display: block;
  margin-bottom: 8px;
}

.selected-client-info,
.selected-service-info {
  padding: 12px;
  background: #f5f7fa;
  border-radius: 4px;
}

.selected-client-info .client-name {
  font-weight: 500;
  margin-right: 8px;
}

.selected-client-info .client-code {
  color: #909399;
  font-size: 12px;
}

:deep(.el-dialog) {
  margin-top: 5vh;
}

:deep(.el-dialog__body) {
  padding: 20px;
}
</style>
